// pages/queryHistory/queryHistory.js
const API = require('../../utils/api.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    customer_id: "",
    queryResultList: [],
    isEmpty: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      customer_id: options.customer_id
    })
    this.requestHistory(options.customer_id)
  },

  requestHistory: function (customer_id) {
    let that = this
    wx.showLoading({
      title: '加载中'
    })
    wx.request({
      url: API.Customer.queryHistory,
      method: "GET",
      data: {
        "customer_id": customer_id
      },
      success (res) {
        let data = res.data
        wx.hideLoading()
        if(data.code == "SUCCESS"){
          if(data.data != ""){
            that.setData({
              isEmpty: false,
              queryResultList: data.data
            })
          }
        }else{
          wx.showToast({
            title: data.message,
            icon: 'none'
          })
        }
      },
      fail (res) {
        wx.hideLoading()
      }
    })
  },

  tapItemDelete: function (e) {
    let that = this
    let index = e.currentTarget.id
    let queryHistoryId = e.currentTarget.dataset.queryhistoryid
    wx.showLoading({
      title: '删除中'
    })
    wx.request({
      url: API.Customer.deleteHistory + "?id=" + queryHistoryId,
      method: "DELETE",
      success (res) {
        wx.hideLoading()
        wx.showToast({
          title: res.data.message,
          icon: "none"
        })
        if(res.data.code == "SUCCESS"){
          that.data.queryResultList.splice(index, 1)
          if(that.data.queryResultList == ""){
            that.setData({
              isEmpty: true
            })
          }else{
            that.setData({
              queryResultList: that.data.queryResultList
            })
          }
        }
      },
      fail (res) {
        wx.hideLoading()
      }
    })
  },

  tapItemDetail: function (e) {
    let productId = e.currentTarget.dataset.productid
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: API.Product.queryById,
      method: "GET",
      data: {
        "id": productId
      },
      success (res) {
        wx.hideLoading()
        if(res.data.code == "SUCCESS") {
          let data = JSON.stringify(res.data.data)
          wx.navigateTo({
            url: '/pages/productDetail/productDetail?data='+data,
          })
        }else{
          wx.showToast({
            title: '加载失败',
            icon: "none"
          })
        }
      },
      fail (res) {
        wx.hideLoading()
      }
    })
  }
})